package controller;

import java.util.List;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import model.Train;

import org.primefaces.event.RowEditEvent;

import service.TrainService;

@ManagedBean
@SessionScoped
public class TrainController {
	
	@EJB
	private TrainService trainService;
  
	private List<Train> allTrains = null;

	private Train train = new Train();
	
	public Train getTrain() {
		return train;
	}
	 
	public List<Train> getAllTrains() {
		if (allTrains == null) {
			allTrains = trainService.findAll();
			return allTrains;
		} else {
			return allTrains;
		}
	}
	
	public void onEdit(RowEditEvent event) {  
		Train editTrain = (Train) event.getObject();
		String result = trainService.update(editTrain);
		allTrains = trainService.findAll();
        FacesMessage msg = new FacesMessage(result);  
        FacesContext.getCurrentInstance().addMessage(null, msg);  
    }  
      
    public void deleteTrain(Train train) {  
    	trainService.delete(train);
    	allTrains = trainService.findAll();
    	FacesMessage msg = new FacesMessage("ok");  
        FacesContext.getCurrentInstance().addMessage(null, msg); 
    }  
    
    public void createTrain() {  
    	String result = trainService.save(this.train);
    	this.train = new Train();
    	allTrains = trainService.findAll();
    	FacesMessage msg = new FacesMessage(result);  
        FacesContext.getCurrentInstance().addMessage(null, msg);  
    }  
}
